package org.sardine.aop;

import java.util.ArrayList;
import java.util.Arrays;

import org.sardine.util.ClassUtils;

/**
 * 
 * 一个AopProxyCreator只能创建一个代理,通过setTarget()方法配置代理对象
 * 
 * 
 * @author BearBear
 *
 */

public class AopProxyCreator extends ProxySupport implements AopProxy{
	
	private ProxyFactory proxyFactory = new DefaultProxyFactroy();
	
	public AopProxyCreator(){
		/**
		 * 目前beans模块还不支持通过带参数构造的方式创建AopProxyCreator对象，只能通过无参数构造方式创建，并用setter的方式设置target属性
		 * 
		 * 当使用beans模块配置文件时，用如下方式配置AopProxyCreator
		 * 1.动态代理，必须配置target属性，即等效调用setTarget()
		 * 2.CGLIB，必须配置target属性或cglib属性，即等效调用setTarget()/setTargetClass()和setCglib(true)
		 * 
		 */
	}
	
	public AopProxyCreator(Object target){
		this(target,false);
	}
	
	public AopProxyCreator(Class targetClass){
		setTargetClass(targetClass);
		setCglib(true);
	}
	
	public AopProxyCreator(Object target,boolean cglib){
		setTarget(target);
		setCglib(cglib);
		if(!cglib){
			setTargetInterfaces(new ArrayList<Class>(Arrays.asList(target.getClass().getInterfaces())));
		}
		
	}

	public Object getProxy() {
		return getProxy(ClassUtils.getDefaultClassLoader());
	}

	public Object getProxy(ClassLoader classLoader) {
		return proxyFactory.createProxy(this).getProxy(classLoader);
	}
	
	//创建CGLIB代理时可以通过构造参数创建（假如有原实例，它将会被覆盖）
	public Object getProxy(Object[] targetConstructorParameters){
		if(!isCglib() || targetConstructorParameters == null || targetConstructorParameters.length == 0){
			return getProxy();
		}
		return proxyFactory.createProxy(this).getProxy(targetConstructorParameters);
		
	}

}
